import { Injectable } from '@nestjs/common';
import * as OSS from 'ali-oss';
import { ossConfig } from '@/config/oss.config';

@Injectable()
export class OssService {
  private client: OSS;

  constructor() {
    this.client = new OSS({
      region: ossConfig.region,
      accessKeyId: ossConfig.accessKeyId,
      accessKeySecret: ossConfig.accessKeySecret,
      bucket: ossConfig.bucket,
      secure: true,
    });
  }

  async generateUploadUrl(filename: string) {
    return await this.client.signatureUrl(filename, {
      method: 'PUT',
      expires: 3600, // 1小时有效
      'Content-Type': 'application/octet-stream',
    });
  }

  async generateAccessUrl(filename: string) {
    return this.client.signatureUrl(filename, {
      expires: 36000,
    });
  }

  async generateDownloadUrl(filename: string) {
    return this.client.signatureUrl(filename, {
      expires: 3600,
      response: {
        'content-disposition': `attachment; filename="${encodeURIComponent(filename)}"`,
      },
    });
  }
}
